// 2025/10/22
// 二叉树的层平均值

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<double> averageOfLevels(TreeNode* root) {
        queue<TreeNode*> q1, q2;
        q1.emplace(root);
        vector<double> ans;
        while(!q1.empty() || !q2.empty())
        {
            double tmp = 0;
            int num = 0;
            if(!q1.empty())
            {
                num = q1.size();
                while(!q1.empty())
                {
                    TreeNode* node = q1.front();
                    q1.pop();
                    tmp += node->val;
                    if(node->left)
                        q2.emplace(node->left);
                    if(node->right)
                        q2.emplace(node->right);
                }
            }
            else
            {
                num = q2.size();
                while(!q2.empty())
                {
                    TreeNode* node = q2.front();
                    q2.pop();
                    tmp += node->val;
                    if(node->left)
                        q1.emplace(node->left);
                    if(node->right)
                        q1.emplace(node->right);
                }
            }
            ans.emplace_back(tmp / num);
        }
        return ans;
    }
};